#!/bin/sh
repos="D:/PROJECT_FOLDER/"
repos_regex="D:\/PROJECT_FOLDER\/"      # in regex format, / -> \/, . -> \.
tomcat="D:/tomcat/"
cd $repos

# version number for patch files (safer to write it in regex format, but not neccessary)
version_tag="8.05.23_v13"
patch='patch_'${version_tag}

# get file list by comparing commits (changes from commitA to commitB, the ^ after commitA is required, branch name can be used as well)
# only files that are added or modified (not deleted) and inside source folder will be added into the list
git diff --diff-filter=ACMRTU commitA^ commitB --name-status | grep '^[MA][ \t]*' | sed 's/^[MA][ \t]*//g' | grep '^source\/' > fileList.txt

# get files list from uncommitted files (new files must be staged to index first)
# git status | egrep "modified|new file" > fileList.txt
# sed -i 's/^#*[ \t]*modified:[ \t]*//g' fileList.txt
# sed -i 's/^#*[ \t]*new file:[ \t]*//g' fileList.txt

# create patch folders
rm -rf ${repos}${patch}
mkdir -p ${repos}${patch}/database/Procs
mkdir -p ${repos}${patch}/database/Script
mkdir -p ${repos}${patch}/database/Seq
mkdir -p ${repos}${patch}/database/Table/alter
mkdir -p ${repos}${patch}/database/Table/create
mkdir -p ${repos}${patch}/database/Table/index
mkdir -p ${repos}${patch}/database/Table/insert
mkdir -p ${repos}${patch}/database/Table/mod
mkdir -p ${repos}${patch}/database/Table/update
mkdir -p ${repos}${patch}/database/Trig
mkdir -p ${repos}${patch}/database/View
mkdir -p ${repos}${patch}/tomcat/common/lib
mkdir -p ${repos}${patch}/tomcat/WEB-INF/classes/com/laconic
cat ${repos}source/database/setup.bat  | sed 's/VERSION_TAG/'${version_tag}'/g' > ${repos}${patch}/database/patch.bat
cat ${repos}utilities/release_seed/patch_tomcat.bat | sed 's/VERSION_TAG/'${version_tag}'/g' > ${repos}${patch}/tomcat/patch.bat

# web files
cd $repos
egrep 'source/laconic/web/' ${repos}fileList.txt > copy.sh
sed -i 's/^source\/laconic\/web\//cp --parent "/g' copy.sh
sed -i 's/$/" '${repos_regex}${patch}'\/tomcat\//g' copy.sh
mv copy.sh source/laconic/web/
cd source/laconic/web/
source copy.sh
rm copy.sh

# class files
cd $repos
egrep 'source/laconic/src/com/laconic/' ${repos}fileList.txt > copy.sh
sed -i 's/^source\/laconic\/src\/com\/laconic\//cp --parent "/g' copy.sh
sed -i 's/\.java/\.class" '${repos_regex}${patch}'\/tomcat\/WEB-INF\/classes\/com\/laconic\//g' copy.sh
mv copy.sh ${tomcat}webapps/laconic/WEB-INF/classes/com/laconic/
cd ${tomcat}webapps/laconic/WEB-INF/classes/com/laconic
source copy.sh
rm copy.sh

# class file for common
cd $repos
if grep -Fq 'source/common/src/com/' ${repos}fileList.txt; then
    cp ${tomcat}common/lib/common.jar ${repos}${patch}/tomcat/common/lib/
fi

# database files
cd $repos
egrep 'source/database/' ${repos}fileList.txt > copy.sh
sed -i 's/^source\/database\//cp --parent "/g' copy.sh
sed -i 's/$/" '${repos_regex}${patch}'\/database\//g' copy.sh
mv copy.sh source/database/
cd source/database/
source copy.sh
rm copy.sh

cd $repos
# rm fileList.txt
